package sinc_wait_notify;

public class MailBox {
	
	private int n;
	private String[] buffer;
	private int in, out, count;
	
	public MailBox(int n){
		this.n = n;
		buffer = new String[n];
		in=0;
		out=0;
		count=0;
	}
	
	public synchronized String receive(int idR){
		while(count==0)
			try{
				wait();
			}
			catch(InterruptedException ignored){}
			
			String ans=buffer[out];
			out=(out+1)%n;
			count--;
			notifyAll();
			return ans;
	}

	public synchronized void send(int idS, String msg){
		while(count==n)
			try{
				wait();
			}
		catch(InterruptedException ignored){}	
		buffer[in] = msg;
		in=(in+1)%n;
		count++;
		notifyAll();
	}
	
	public synchronized void send(int idS, String msg, long timeout){
		while(count==n)
			try{
				wait();
			}
		catch(InterruptedException ignored){}	
		buffer[in] = msg;
		in=(in+1)%n;
		count++;
		notifyAll();
	}
}
